<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        // 二叉树的右视图
        function Node(val) {
            this.val = val;
            this.left = null;
            this.right = null;
        }
        var a = new Node(1)
        var b = new Node(null)
        var c = new Node(2)
        var d = new Node(3)
        var e = new Node(4)
        var f = new Node(5)
        var g = new Node(6)
        a.left = b
        a.right = c
        b.left = d
        b.right = e
        c.left = f
        c.right = g
        /* 
            时间复杂度：O(n)
            空间复杂度：O(n)
        */
        var rightSideView = function (root) {
            let res = []
            if (!root) return res
            let queue = [] 
            queue.push(root)
            while (queue.length > 0) {
                let length = queue.length
                let curLevel = []
                for (let i = 0; i < length; i++) {
                    let node = queue.shift()
                    curLevel.push(node.val)
                    node.left && queue.push(node.left)
                    node.right && queue.push(node.right)
                }
                // 只把每一层的最后一个元素push进去，就是右视图这题的解法了，上面代码和层序遍历是一样的
                res.push(curLevel[curLevel.length - 1])
            }
            return res
        };
        console.log(rightSideView(a));
    </script>
</body>

</html>